﻿<!DOCTYPE html>
<html lang="zh-cn">

	<head>
		<meta charset="utf-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge">
		<meta name="viewport" content="width=device-width,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no" />
		<title>WIFI打卡</title>
		<link type="text/css" href="css/punchtheclock.css?v=2" rel="stylesheet" />
		<script type="text/javascript" src="./js/jquery-2.2.4.min.js"></script>
		<script src="../assets/js/m.js"></script>
		<script src="http://res.wx.qq.com/open/js/jweixin-1.2.0.js"></script>
		<link href="../assets/js/plugins/layer_mobile/need/layer.css" rel="stylesheet" />
		<script src="../assets/js/plugins/layer_mobile/layer.js"></script>
		<script src="//cdn.bootcss.com/eruda/1.4.2/eruda.min.js"></script>
		<script>
			eruda.init();
		</script>
	</head>

	<body>
		<div class="main">
			<div class="userInfo">
				<div class="userName"><span class="name">未知用户</span>(<span class="id">0</span>)</div>
				<div class="currentDate">

				</div>
			</div>
			<div class="checkinInfo">
				<div class="checkinTips" style="width: 100%;text-align: left;"><span>请连接公司有效wifi进行打卡(km,km-office)</span></div>
				<div class="topPart">
					<div class="houseIcon houseOk">
						<img src="img/checkin/house.png" />
					</div>
					<div class="houseIcon houseError">
						<img src="img/checkin/house2.png" />
					</div>
					<div class="tips_in">
						您已在打卡范围内
					</div>
					<div class="tips_notIn">
						您不在打卡范围内
					</div>
					<div class="wifi wifiOk">
						wifi：?
					</div>
					<div class="wifi wifiError">
						请连接公司WIFI-KM
					</div>
					<div class="checkin" style="cursor: pointer;">
						<div class="icon">
							<div class="currentTime" id="currentTime">??:??</div>
							<div class="checkinType">打卡</div>
						</div>
					</div>
				</div>
				<div class="history">
					<div class="title">
						打卡记录
					</div>
					<div class="historyList">
					</div>
				</div>
			</div>
		</div>
		<script>
			var wifi = null;
			var user = null;
			var networkTime = null;
			var timeSpan = null;

			var macs = [
				"90:3a:72:4c:8e:08","90:3a:72:0c:8e:08","90:3a:72:cc:8e:08",
				"90:3a:72:4c:8e:0c","90:3a:72:0c:8e:0c","90:3a:72:cc:8e:0c",
				"34:8f:27:b3:dd:78","34:8f:27:33:dd:78","34:8f:27:73:dd:78",
				"34:8f:27:b3:dd:7c","34:8f:27:33:dd:7c","34:8f:27:73:dd:7c",
				"34:8f:27:51:35:58","34:8f:27:11:35:58","34:8f:27:d1:35:58",
				"34:8f:27:51:35:5c","34:8f:27:11:35:5c","34:8f:27:d1:35:5c",
				"34:8f:27:b3:fd:a8","34:8f:27:33:fd:a8","34:8f:27:73:fd:a8",
				"34:8f:27:b3:fd:ac","34:8f:27:33:fd:ac","34:8f:27:73:fd:ac",
				"24:79:2a:96:3a:a8","24:79:2a:16:3a:a8","24:79:2a:56:3a:a8",
				"24:79:2a:96:3a:ac","24:79:2a:16:3a:ac","24:79:2a:56:3a:ac",
				"34:8f:27:51:a3:d8","34:8f:27:11:a3:d8","34:8f:27:d1:a3:d8",
				"34:8f:27:51:a3:dc","34:8f:27:11:a3:dc","34:8f:27:d1:a3:dc",
				"24:79:2a:58:aa:c8","24:79:2a:18:aa:c8","24:79:2a:d8:aa:c8",
				"24:79:2a:58:aa:cc","24:79:2a:18:aa:cc","24:79:2a:d8:aa:cc",
				"90:3a:72:4c:93:78","90:3a:72:0c:93:78","90:3a:72:cc:93:78",
				"90:3a:72:4c:93:7c","90:3a:72:0c:93:7c","90:3a:72:cc:93:7c",
				"90:3a:72:4c:8c:a8","90:3a:72:0c:8c:a8","90:3a:72:cc:8c:a8",
				"90:3a:72:4c:8c:ac","90:3a:72:0c:8c:ac","90:3a:72:cc:8c:ac",
				"24:79:2a:98:d6:c8","24:79:2a:18:d6:c8","24:79:2a:58:d6:c8",
				"24:79:2a:98:d6:cc","24:79:2a:18:d6:cc","24:79:2a:58:d6:cc",
				"24:79:2a:58:eb:38","24:79:2a:18:eb:38","24:79:2a:d8:eb:38",
				"24:79:2a:58:eb:3c","24:79:2a:18:eb:3c","24:79:2a:d8:eb:3c",
				"34:8f:27:76:b9:38","34:8f:27:36:b9:38","34:8f:27:f6:b9:38",
				"34:8f:27:76:b9:3c","34:8f:27:36:b9:3c","34:8f:27:f6:b9:3c",
				"34:8f:27:76:f9:48","34:8f:27:36:f9:48","34:8f:27:f6:f9:48",
				"34:8f:27:76:f9:4c","34:8f:27:36:f9:4c","34:8f:27:f6:f9:4c",
				"34:8f:27:76:8b:f8","34:8f:27:36:8b:f8","34:8f:27:f6:8b:f8",
				"34:8f:27:76:8b:fc","34:8f:27:36:8b:fc","34:8f:27:f6:8b:fc",
				"34:8f:27:73:a3:e8","34:8f:27:33:a3:e8","34:8f:27:f3:a3:e8",
				"34:8f:27:73:a3:ec","34:8f:27:33:a3:ec","34:8f:27:f3:a3:ec",
				"40:31:3c:2b:33:cb","40:31:3c:2b:33:cc","24:79:2a:98:aa:c8",
				"24:79:2a:98:aa:cc","34:8f:27:b3:a3:ec","78:44:fd:d0:44:82",
				"24:79:2a:98:eb:38","78:44:fd:d0:42:b2","78:44:fd:d0:46:e0",
				"24:79:2a:98:eb:3c","78:44:fd:d0:40:00","34:8f:27:91:35:58",
				"34:8f:27:91:35:5c","34:8f:27:91:a3:d8","34:8f:27:91:a3:dc",
				"34:8f:27:b6:8b:f8","34:8f:27:b6:8b:fc","34:8f:27:b6:b9:38",
				"34:8f:27:b6:b9:3c","34:8f:27:b6:f9:48","34:8f:27:b6:f9:4c",
				"90:3a:72:8c:8c:a8","90:3a:72:8c:8c:ac","90:3a:72:8c:8e:08",
				"90:3a:72:8c:8e:0c","90:3a:72:8c:93:78","90:3a:72:8c:93:7c"
			];

			//获取地址栏参数
			var getUrlParam = function(name) {
				var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
				var r = window.location.search.substr(1).match(reg);
				if(r != null) return unescape(r[2]);
				return null;
			};

			//格式化时间小于10的部分
			var formatTimeIfLessThanTen = function(i) {
				if(i < 10) {
					i = "0" + i;
				}
				return i;
			};

			//设置一个动态时钟
			var setClock = function() {
				//现在的时间加上与网络时间的差，就是网络时间
				var date = new Date(new Date().getTime() + timeSpan);
				var h = formatTimeIfLessThanTen(date.getHours());
				var m = formatTimeIfLessThanTen(date.getMinutes());
				var s = formatTimeIfLessThanTen(date.getSeconds());
				//document.getElementById('currentTime').innerHTML = h + ":" + m + ":" + s
				document.getElementById('currentTime').innerHTML = h + ":" + m;
				var t = setTimeout('setClock()', 500);
			};

			//CSharp的DateTime格式转JS的Date格式
			var cSharpTimeToJsDate = function(cSharpTime) {
				var t = cSharpTime.replace("T", " ");
				t = t.replace(/-/g, "/");
				var date = new Date(t);
				return date;
			};

			//转换CSharp DateTime格式变成 HH:mm格式
			var CSharpTimeToHHmm = function(date) {
				var tdate = cSharpTimeToJsDate(date);
				return formatDateToHHmm(tdate);
			};

			//转换Date格式变成 HH:mm格式 
			var formatDateToHHmm = function(date) {
				var h = formatTimeIfLessThanTen(date.getHours());
				var m = formatTimeIfLessThanTen(date.getMinutes());
				return h + ":" + m;
			};

			//转换时间戳到 HH:mm格式 
			function timestampToHHmm(timestamp) {
				//timestamp是整数，否则要parseInt转换
				var time = new Date(timestamp);
				return formatDateToHHmm(time);
			};

			//转换时间戳到打卡格式 
			function getCheckInTime() {
				var time = new Date(new Date().getTime() + timeSpan);
				var y = time.getFullYear();
				var m = time.getMonth() + 1;
				var d = time.getDate();

				var h = formatTimeIfLessThanTen(time.getHours());;
				var mm = formatTimeIfLessThanTen(time.getMinutes());
				var s = formatTimeIfLessThanTen(time.getSeconds());
				return y + "-" + m + "-" + d + " " + h + ":" + mm + ":" + s;
			};

			//Mac是否在列表中
			var isMacInList = function(mac) {
				for(var i = 0; i < macs.length; i++) {
					if(mac === macs[i]) {
						return true;
					}
				}
				return false;
			};

			//封装的alert
			var layerAlert = function(msg) {
				layer.open({
					style: 'border:none; background-color:#fff; color:#000;',
					content: msg
				});
			};

			var layerAlertCallback = function(msg, doEnd) {
				layer.open({
					style: 'border:none; background-color:#fff; color:#000;',
					content: msg,
					end: function(index) {
						doEnd();
					}
				});
			};

			var getHistoryItem = function(tTime, wifiName) {
				var html = '<div class="historyItem">' +
					'<div class="time">' + tTime + '</div>' +
					'<div class="text">WIFI：' + wifiName + ' 打卡</div>' +
					'<div class="lineBlock">' +
					'<div class="line"></div>' +
					'</div>' +
					'</div>';
				return html;
			};

			var setNetworkOkStyle = function() {
				//房子图标
				$('.wifiOk').show();
				$('.wifiError').hide();
				//打卡范围
				$('.houseOk').show();
				$('.houseError').hide();
				//黑色字体
				$('.tips_in').show();
				$('.tips_notIn').hide();
			};

			var setNetworkErrorStyle = function() {
				//房子图标
				$('.wifiError').show();
				$('.wifiOk').hide();
				//打卡范围
				$('.houseError').show();
				$('.houseOk').hide();
				//黑色字体
				$('.tips_notIn').show();
				$('.tips_in').hide();
			};

			//获取已连接的Wifi信息
			var getConnectedWifi = function() {
				wx.getConnectedWifi({
					success: function(res) {
						wifi = res.wifi;
						$('.wifiOk').text("wifi：" + res.wifi.SSID);
						if(isMacInList(res.wifi.BSSID)) {
							setNetworkOkStyle();
							setTimeout('getConnectedWifi()', 1000)
						} else {
							setNetworkErrorStyle();
							setTimeout('getConnectedWifi()', 1000)
							//							layerAlertCallback("本wifi无法打卡，请先连接指定的wifi然后重新打卡", function() {
							//								setTimeout('getConnectedWifi()', 500)
							//							});
						}
					},
					fail: function(res) {
						console.log("getConnectedWifi失败：", res);
						setNetworkErrorStyle();
						if(res.errCode === 12006) {
							layerAlertCallback("请打开GPS定位服务，然后重新进入WIFI打卡应用", function() {
								setTimeout('getConnectedWifi()', 500)
							});
						} else {
							setTimeout('getConnectedWifi()', 1000)
							//							layerAlertCallback("无法获取wifi信息，请先连接指定的wifi然后重新打卡", function() {
							//								setTimeout('getConnectedWifi()', 500)
							//							});
						}

					}
				});
			};

			$(function() {
				//自动调整historyList高度
				var tHeight = $('.main').outerHeight() -
					$('.userInfo').outerHeight() -
					$('.checkinTips').outerHeight() -
					$('.topPart').outerHeight() -
					$('.history .title').outerHeight() -
					40; //margin 有 20，还有20哪来的 

				$('.historyList').css('height', tHeight);

				//初始化m.js
				new window.Kmer({ "AppRootPath": "", "CurrentUrl": "" });

				var code = getUrlParam("code") || "";
				var config = getUrlParam("state") || "";


				//注入配置
				var url3 = window.location.href;
				Y.API3("WXBase", "GetConfig", { "url": url3, "wxConfig": config }, function(data) {
					if(data.Success == false) {
						console.log("WXBase GetConfig失败", data.Message);
					} else {
						wx.config({
							//beta: true,// 必须这么写，否则wx.invoke调用形式的jsapi会有问题
							debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
							appId: data.corpId, // 必填，企业微信的corpID
							timestamp: data.timeStamp, // 必填，生成签名的时间戳
							nonceStr: data.nonceStr, // 必填，生成签名的随机串
							signature: data.signature, // 必填，签名，见附录1
							jsApiList: [
								"onMenuShareWechat", "onMenuShareAppMessage", "hideOptionMenu", "startWifi", "getConnectedWifi"
							]
							// 必填，需要使用的JS接口列表，所有JS接口列表见附录2
						});
					}
				});

				//准备微信相关（包括wifi）
				wx.ready(function() {
					// config信息验证后会执行ready方法，所有接口调用都必须在config接口获得结果之后，config是一个客户端的异步操作，所以如果需要在页面加载时就调用相关接口，则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口，则可以直接调用，不需要放在ready函数中。
					//分享给朋友接口

					/* begin禁用微信分享功能 */
					function onBridgeReady() {
						WeixinJSBridge.call('hideOptionMenu');
					}

					if(typeof WeixinJSBridge == "undefined") {
						if(document.addEventListener) {
							document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
						} else if(document.attachEvent) {
							document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
							document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
						}
					} else {
						onBridgeReady();
					}
					/* end禁用微信分享功能 */

					wx.checkJsApi({
						jsApiList: ['startWifi'], // 需要检测的JS接口列表，所有JS接口列表见附录2,
						success: function(res) {
						 	//console.log("checkJsApi success",res);
							// 以键值对的形式返回，可用的api值true，不可用为false
							// 如：{"checkResult":{"chooseImage":true},"errMsg":"checkJsApi:ok"}
						},
						fail: function(res) {
						 console.log("checkJsApi fail",res);
							// 以键值对的形式返回，可用的api值true，不可用为false
							// 如：{"checkResult":{"chooseImage":true},"errMsg":"checkJsApi:ok"}
						},
						complete: function(res) {
						 	//console.log("checkJsApi complete",res);
							// 以键值对的形式返回，可用的api值true，不可用为false
							// 如：{"checkResult":{"chooseImage":true},"errMsg":"checkJsApi:ok"}
						}
					});
					
					//初始化wifi模块（在Android必须，在IOS好像不用）
					wx.startWifi({
						success: function(res) {
							getConnectedWifi();
						},
						fail: function(res) {
							console.log("startWifi fail", res);
						},
						complete: function(res) {
							//console.log("wx complete");
							//console.log("startWifi complete", res);
						},
					});

				});
				
				wx.error(function (res) {
					console.log("wx.error",res);
				});

				//获取用户信息
				Y.API2("WxPunchClock", "GetUserInfo", { "Code": code, "wxConfig": config }, function(data) {
					if(data.Success == false) {
						console.log("GetUserInfo 失败", data.Message);
					} else {
						//用户信息
						user = data.users || null;
						if(user != null) {
							$('.userName .name').text(user.UserName);
							$('.userName .id').text(user.UserId);
							var today = new Date();
							var y = today.getFullYear();
							var m = today.getMonth() + 1;
							var d = today.getDate();
							$('.currentDate').text(y + "年" + m + "月" + d + "日");
						}

						//网络时间操作
						var time = data.netWorkTime || null;
						if(time != null) {
							//把网络时间转成JS时间
							networkTime = cSharpTimeToJsDate(time);
							//算出本地时间跟网络时间的时间差，用以校准
							timeSpan = (networkTime.getTime() - new Date().getTime());

							//有网络时间了，开始设置动态时钟
							setClock();
						}

						//打卡记录
						var checkInList = data.punchs || null;
						if(checkInList != null) {
							var html = "";
							for(var i = 0; i < checkInList.length; i++) {
								var tTime = CSharpTimeToHHmm(checkInList[i].checkin_time);
								html += getHistoryItem(tTime, checkInList[i].wifiname);
							}
							$('.historyList').html(html);
						}
					}
				});

				//打卡
				var doPunchCheck = function() {
					if(user == null || wifi == null) {
						layerAlert("用户信息或者网络异常");
						console.log("用户信息或者网络异常", user, wifi);
						return false;
					}

					var tempTime = getCheckInTime();
					var data = {
						userid: user.UserId,
						checkin_time: tempTime,
						wifimac: wifi.BSSID,
						wifiname: wifi.SSID
					};
					Y.API2("WxPunchClock", "PunchCheck", data, function(data) {
						if(data.Success == false) {
							console.log("PunchCheck 失败", data.Message);
						} else {
							//var d = JSON.stringify(data.Data);
							if(data === 0) {
								layerAlert("打卡成功");
								var tempTime = formatDateToHHmm(new Date(new Date().getTime() + timeSpan));
								var html = getHistoryItem(tempTime, wifi.SSID);
								$('.historyList').append(html);
							} else {
								layerAlert("打卡失败:" + data);
							}
						}
					});
				};

				$(document).on('click', '.checkin .icon', function() {

					//获取已连接的Wifi信息
					wx.getConnectedWifi({
						success: function(res) {
							wifi = res.wifi;
							$('.wifiOk').text("wifi：" + res.wifi.SSID);
							if(isMacInList(res.wifi.BSSID)) {
								setNetworkOkStyle();
								doPunchCheck();
							} else {
								setNetworkErrorStyle();
							}
						},
						fail: function(res) {
							setNetworkErrorStyle();
							console.log("getConnectedWifi > fail",res);
							if(res.errCode === 12006) {
								layerAlert("请打开GPS定位服务，然后重新进入WIFI打卡应用");
							}
							if(res.errCode === 12010) {
								layerAlert("请打开GPS定位服务，然后重新进入WIFI打卡应用");
							}
							else if(res.errMsg === "getConnectedWifi:no wifi is connected.") {
								layerAlert("请先连接指定wifi，然后重新打卡");
							} else {
								layerAlert("没有找到可用wifi，无法打卡");
							}
						}
					});
				});
			});
		</script>
	</body>

</html>